package com.hm.hall.commons.util;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.Logger;
import org.springframework.util.DigestUtils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Random;

/**
 * OSS文件存储的相关上传方法
 *
 * @author wei
 */
public class OssUtils {

    private static final String ACCESS_ID = "LTAICZpesVguZb7c";
    private static final String ACCESS_KEY = "KVkRrUWeZzjo57C7DZ3LhRIZgYdKqP";
    private static final String bucket_job_pic = "hall";
    private static Logger logger = Logger.getLogger(OssUtils.class);

    /**
     * 上传照片到oss
     *
     * @param fileContent byte[] 文件内容
     * @param extName     扩展名， 如  jpg  png
     * @return 上传后的oss图片访问 url ; 上传失败返回null
     */
    public static String uploadPICAssignExtName(byte[] fileContent, String extName) {
        try {
            String fileName = System.currentTimeMillis() + "_" + DigestUtils.md5DigestAsHex(String.valueOf(new Random().nextInt(999999)).getBytes("utf-8")).toUpperCase() + "." + extName;
            return uploadPIC(fileContent, fileName);
        } catch (UnsupportedEncodingException e) {
            logger.error("oss上传失败", e);
            return null;
        }
    }

    /**
     * 上传照片到oss
     *
     * @param fileContent byte[] 文件内容
     * @param fileName    文件名
     * @return 上传后的oss图片访问 url ; 上传失败返回null
     */
    public static String uploadPIC(byte[] fileContent, String fileName) {
        // 使用默认的OSS服务器地址创建OSSClient对象。
        OSSClient client = new OSSClient(ACCESS_ID, ACCESS_KEY);
        try {
            String key = fileName;
            ObjectMetadata objectMeta = new ObjectMetadata();
            objectMeta.setContentLength(fileContent.length);
            client.putObject(bucket_job_pic, key, new ByteArrayInputStream(fileContent), objectMeta);
            return "https://hall.oss-cn-hangzhou.aliyuncs.com/" + key;
        } catch (Exception e) {
            logger.error("oss上传失败", e);
            return null;
        }
    }


    public static void main(String[] args) {
        // System.out.println(uploadwx2oss("http://q.qlogo.cn/qqapp/1104872133/E9A4CCB5B85B23AD25C7BD33E6E5C6B6/100"));

        long beginTime;
        boolean isNetFileAvailable;
        String url = "http://127.0.0.1/gift/square.html http://job-pic.oss-cn-hangzhou.aliyuncs.com/1403084711141_3e5aecceac207be98c3ea583d2c4e330.jpg";
        String url2 = "http://img.froup.net/1403084711141_3e5aecceac207be98c3ea583d2c4e330.jpg";
        String url3 = "http://img.froup.net/1403084711141_3e5aecceac207be98c3ea583d2c4e330.jpg";
        String urls[] = {url2, url3, url3};

        for (int i = 0; i < 100; i++) {


            beginTime = System.currentTimeMillis();
            isNetFileAvailable = isNetFileExists(urls[i % 3]);
            System.out.println(String.format("%s :  耗时:%s 是否存在 %s,exists,%s,", i, System.currentTimeMillis() - beginTime, isNetFileAvailable, i % 3));

        }


    }

    /**
     * 第三方登录登陆的头像抓到oss上
     *
     * @param url 微信url
     * @return 新的oss图片完整链接url  .
     * eg.http://img.froup.net/1415443584687_a5e29613950421c3a7ba19fb85b40d42.jpeg
     * 导入失败返回默认头像img.froup.net/avatar_default.png
     */
    public static String uploadwx2oss(String url) {
        String picUrl = uploadPic2oss(getImageByteByUrl(url));
        logger.info("oss upload success" + picUrl);
        return picUrl == null ? "http://img.froup.net/avatar_default.png" : picUrl;
    }

    /**
     * 上车图片到 oss
     *
     * @return oss图片完整链接url  .
     */
    public static String uploadPic2ossByBase64(String imgBase64) {
        return uploadPic2oss(OssUtils.getImageByteByBase64(imgBase64));
    }

    /**
     * 上车图片到 oss
     *
     * @return oss图片完整链接url  .
     */
    public static String uploadPic2oss(byte[] imageBayes) {
        try {
            String key = System.currentTimeMillis() + "_" + DigestUtils.md5DigestAsHex(String.valueOf(new Random().nextInt(999999)).getBytes("utf-8")).toUpperCase() + ".jpg";
            // 使用默认的OSS服务器地址创建OSSClient对象。
            OSSClient client = new OSSClient(ACCESS_ID, ACCESS_KEY);
            ObjectMetadata objectMeta = new ObjectMetadata();
            objectMeta.setContentLength(imageBayes.length);

            client.putObject(bucket_job_pic, key, new ByteArrayInputStream(imageBayes), objectMeta);
            return "https://hall.oss-cn-hangzhou.aliyuncs.com/" + key;
        } catch (Exception e) {
            logger.error("图片上传oss失败", e);
            return null;
        }
    }

    /**
     * 上车图片到 oss
     *
     * @return oss图片完整链接url  .
     */
    public static String uploadPic2oss(byte[] imageBayes, String targetPathName) {
        try {
            logger.info("开始上传 --> " + targetPathName);
            String key = targetPathName;
            // 使用默认的OSS服务器地址创建OSSClient对象。
            OSSClient client = new OSSClient(ACCESS_ID, ACCESS_KEY);
            ObjectMetadata objectMeta = new ObjectMetadata();
            objectMeta.setContentLength(imageBayes.length);
            logger.info("上传完成 --> " + targetPathName);
            client.putObject(bucket_job_pic, key, new ByteArrayInputStream(imageBayes), objectMeta);
            return "http://img.froup.net/" + key;
        } catch (Exception e) {
            logger.error("图片上传oss失败, url=");
            return null;
        }
    }


    /**
     * 根据地址获得数据的字节流
     *
     * @param strUrl 网络连接地址
     */
    public static byte[] getImageByteByUrl(String strUrl) {
        try {
            strUrl = strUrl.replaceAll("https", "http");
            URL url = new URL(strUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5 * 1000);
            InputStream inStream = conn.getInputStream();//通过输入流获取图片数据
            byte[] btImg = readInputStream(inStream);//得到图片的二进制数据
            logger.info(btImg.length);
            return btImg;
        } catch (Exception e) {
            logger.error(e);
        }
        return null;
    }

    /**
     * 根据base64 获得数据的字节流
     */
    public static byte[] getImageByteByBase64(String imgBase64) {
        if (imgBase64.contains("base64,")) {
            String[] d = imgBase64.split("base64,");
            return Base64.decodeBase64(d[1]);
        }
        return Base64.decodeBase64(imgBase64);
    }


    /**
     * 从输入流中获取数据
     *
     * @param inStream 输入流
     * @return
     * @throws Exception
     */
    private static byte[] readInputStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        inStream.close();
        return outStream.toByteArray();
    }

    public static String urlsafeB64encode(String text) {
        text = Base64.encodeBase64String(text.getBytes());
        text = text.replaceAll("\\+", "-");
        text = text.replaceAll("\\/", "_");
        return text;
    }


    /**
     * 判断url 资源是否存在
     */
    public static boolean isNetFileExists(String url) {
        try {
            HttpURLConnection.setFollowRedirects(false); //设置此类是否应该自动执行 HTTP 重定向（响应代码为 3xx 的请求）。
            HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();//到 URL 所引用的远程对象的连接
           /* 设置 URL 请求的方法， GET POST HEAD OPTIONS PUT DELETE TRACE 以上方法之一是合法的，具体取决于协议的限制。*/
            con.setRequestMethod("HEAD");
            return (con.getResponseCode() == HttpURLConnection.HTTP_OK);//从 HTTP 响应消息获取状态码
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


}

